<?php

namespace App\Http\Middleware;

use Closure;

class CheckUserLogin
{
    public function handle($request, Closure $next)
    {
        $user = getLoginUser();

        if (empty($user)) {
            if ($request->isMethod('post')) return jsonFailed('请先登录', 401);
            $config = Config('common.wxmp');
            $previous = url()->full();
            $callbackUrl = Config('app.url') . '/shop/weixin_callback_url?previous=' . urlencode($previous); // 登录成功返回的URL
            $OAuth = new \Yurun\OAuthLogin\Weixin\OAuth2($config['AppID'], $config['AppSecret'], $callbackUrl);
            $OAuth->scope = 'snsapi_base'; // 设置为静默授权
            $url = $OAuth->getWeixinAuthUrl();
            $state = $OAuth->state;
            session(['session_weixin_state' => $OAuth->state]);
            return redirect($url);
        }

        $request->attributes->add(['user' => $user]);
        return $next($request);
    }
}
